<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
        show-icon>
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类级联选择器 -->
          <el-cascader
              v-model="selectedCateKey"
              :options="cateList"
              :props="{ expandTrigger: 'hover',
                        value: 'cat_id',
                        label: 'cat_name',
                        children: 'children'
                      }"
              @change="handleChange"
              clearable
              class="casc">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
       <el-tabs v-model="activeName" @tab-click="handleClick">
         <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary"
                     :disabled="isBtnDisabled"
                     @click="addAttrDialog = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals"
                        :key="index" closable
                        @close="handleClosed(index, scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini"
                           type="danger"
                           icon="el-icon-delete"
                           @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary"
                     :disabled="isBtnDisabled"
                     @click="addAttrDialog = true">添加属性</el-button>
          <!-- 添加静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals"
                        :key="index" closable
                        @close="handleClosed(index, scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini"
                           type="danger"
                           icon="el-icon-delete"
                           @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addAttrDialog"
      width="50%"
      @close="addAttrDialogClosed">
      <!-- 添加参数对话框 -->
      <el-form :model="addAttrForm"
               :rules="addAttrFormRules"
               ref="addAttrFormRef"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editAttrDialog"
      width="50%"
      @close="editDialogClosed">
      <el-form :model="editAttrForm"
               :rules="editAttrFormRules"
               ref="editAttrFormRef"
               label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  data() {
    return {
      //商品分类列表
      cateList: [],
      //级联选择框双向绑定到的数组
      selectedCateKey: [],
      //被激活的页签名称
      activeName: 'many',
      //动态参数数据
      manyTabData: [],
      //静态属性数据
      onlyTabData: [],
      //控制添加对话框的显示与隐藏
      addAttrDialog: false,
      //添加参数的表单对象
      addAttrForm: {
        attr_name: ''
      },
      //验证规则
      addAttrFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      //控制修改对话框的显示与隐藏
      editAttrDialog: false,
      //修改表单数据对象
      editAttrForm: {},
      //验证规则
      editAttrFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取所有的商品分类列表
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if(res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
    },
    //级联选择框中选项变化触发
    handleChange() {
      this.getParamsData()
    },
    //tab 页签点击事件的处理函数
    handleClick() {
      console.log(this.activeName);
      this.getParamsData()
    },
    //获取参数列表的函数
    async getParamsData() {
      //说明选中的不是三级分类
      if(this.selectedCateKey.length !== 3) {
        this.selectedCateKey = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      //选中的是三级分类
      console.log(this.selectedCateKey);
      //根据所选分类id，和当前所处面板 获取对应的参数
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {sel: this.activeName}
      })
      if(res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //默认隐藏文本输入框
        item.inputVisible = false
        //文本框中输入的内容
        item.inputValue = ''
      })
      if(this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    //监听添加对话框的关闭事件
    addAttrDialogClosed() {
      this.$refs.addAttrFormRef.resetFields()
    },
    //点击按钮添加参数
    addParams() {
      this.$refs.addAttrFormRef.validate(async valid => {
        if(!valid) {
          return
        }
        const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addAttrForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.addAttrDialog = false
        this.getCateList()
      })
    },
    //点击按钮展示修改对话框
    async showEditDialog(id) {
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: {attr_sel: this.activeName}
      })
      if(res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      this.editAttrForm = res.data
      this.editAttrDialog = true
    },
    //重置修改表单
    editDialogClosed() {
      this.$refs.editAttrFormRef.resetFields()
    },
    //点击修改按钮保存数据
    editParams() {
      this.$refs.editAttrFormRef.validate(async valid => {
        if(!valid) {
          return
        }
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editAttrForm.attr_id}`, {
          attr_name: this.editAttrForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
        this.getCateList()
        this.editAttrDialog = false
      })
    },
    //根据id删除对应数据项
    async removeParams(id) {
      const confirmResult = await this.$confirm('确定删除该参数信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirmResult !== 'confirm') {
        return this.$message.info('取消了删除操作')
      }
      const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if(res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getCateList()
    },
    //文本框失去焦点或按下enter都会触发
    async handleInputConfirm(row) {
      console.log(row);
      if(row.inputValue.trim().length ===0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //如果没有return 在做后续处理
      row.attr_vals.push(row.inputValue.trim())

      row.inputValue = ''
      row.inputVisible = false
      //需要发起请求 保存这次操作
      this.saveAttrVals(row)
    },
    //将对attr_vals的数据操作保存到数据库中
    async saveAttrVals(row) {
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    //点击控制为何种模式显示
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //根据对应索引值删除标签项
    handleClosed(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    //如果按钮需要被禁用 返回true
    isBtnDisabled () {
      if(this.selectedCateKey.length !== 3) {
        return true
      } else {
        return false
      }
    },
    //当前选中的三级分类的id
    cateId() {
      if(this.selectedCateKey.length === 3) {
        return this.selectedCateKey[this.selectedCateKey.length - 1]
      }
      return null
    },
    //动态生成对话框标题
    titleText() {
      if(this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.casc {
  margin-left: 10px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
